<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
    <form>
        用户名：<input type="text" name="username" id="username"><span id="tip"></span><br/>
        用户密码：<input type="password" name="password" id="password"><br/>
        用户角色：<select id="role" ></select><br/>
        <input type="button" value="添 加" id="submit">
    </form>
</body>
<script>
    $(function (){
        $("#role").empty();
        $.ajax({
            type:"post",
            url:"/user/getAllRole",
            success:function (res){
                for (const re of res) {
                    $("#role").append($("<option></option>").val(re.roleid).text(re.rolename))
                }
            }
        })
    })
    $("#submit").click(function (){
        $.ajax({
            type:"post",
            url:"/user/register",
            contentType: "application/json", // 设置内容类型为 JSON
            data: JSON.stringify({
                username: $("#username").val(),
                password: $("#password").val(),
                role:{
                    roleid:$("#role").val()
                }
            }),
            success: function (res){
                if (res=="true"){
                    location.href="userInfo.html"
                } else {
                    alert("添加失败")
                }
            }
        })
    })
    $(function (){
        $("#username").blur(function (){
            if(!$("#username").val()){
                $("#tip").html("用户不能为空").css("color","red");
                $("#submit").prop("disabled", true);
            } else {
                $.ajax({
                    type: "post",
                    url: "/user/checkName",
                    data: {
                        "username": $("#username").val()
                    },
                    success: function (res) {
                        if (res == 'true') {
                            $("#tip").html("用户已存在").css("color", "red");
                            $("#submit").prop("disabled", true);
                        } else {
                            $("#tip").html("可以").css("color", "green");
                            $("#submit").prop("disabled", false);
                        }
                    }
                })
            }
        })
    })
</script>

</html>
